package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.dao.ClassificationDao;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.IClassificationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cc.linker.steplink.crm.merchant.service.ShopGroupService.GROUP_BELONG_ID;

@Slf4j
@Service
public class ClassificationServiceImpl implements IClassificationService {
    @Autowired
    private ClassificationDao classificationDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void insertClassification(Map<String, Object> param) {
        Integer count = classificationDao.countClassificationName(param);
        if (count > 0) {
            throw GlobalException.build("名称重复");
        }
        classificationDao.insertClassification(param);
    }

    @Override
    public void updateClassification(Map<String, Object> param) {
        Integer count = classificationDao.countClassificationName(param);
        if (count > 0) {
            throw GlobalException.build("名称重复");
        }
        classificationDao.updateClassification(param);
    }

    @Override
    public void deleteClassification(Map<String, Object> param) {
        // 删除类目
        classificationDao.deleteClassification(param);
        // 更新此类目下商品类目信息为空
        classificationDao.deleteGoodsClassification(param);
    }

    @Override
    public PageInfo listClassification(Map<String, Object> param) {
        Integer pageIndex = (Integer) param.get("pageIndex");
        Integer pageSize = (Integer) param.get("pageSize");
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> maps = classificationDao.listClassification(param);
        return new PageInfo<>(maps);
    }

    @Override
    public List<Map<String, Object>> listGoodsClassification(Map<String, Object> param) {
        return classificationDao.listClassification(param);
    }

    @Override
    public PageInfo listGoodsByGroupId(Map<String, Object> param) {
        Object groupId = param.get("groupId");
        if (groupId != null && Integer.valueOf(groupId.toString()) > 0) {
            Integer integer = classificationDao.countGroupByGroupId(groupId.toString());
            if (integer == 0) {
                Object o = redisTemplate.opsForHash().get(GROUP_BELONG_ID, groupId.toString());
                if (o != null) {
                    throw GlobalException.notFound(o.toString());
                } else {
                    throw GlobalException.notFound();
                }
            }
        }
        Integer pageIndex = (Integer) param.get("pageIndex");
        Integer pageSize = (Integer) param.get("pageSize");
        if(null == pageIndex) {
            pageIndex = 1;
        }
        if(null == pageSize) {
            pageSize = 10;
        }

        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> maps;
        Integer groupIsOrg;
        if (this.judge(param)) {
            // 默认/全部分组
            groupIsOrg = Integer.valueOf(param.get("groupIsOrg").toString());
        } else {
            groupIsOrg = classificationDao.countGroupIsOrg(param);
        }
        if (groupIsOrg == null) {
            groupIsOrg = 1;
        }
        if (groupIsOrg == 1) {
            maps = classificationDao.listGoodsByGroupId(param);
        } else {
            maps = classificationDao.listGoodsByGroupIdAndCustomerId(param);
        }

//        if(null != param.get("tipsShow")){
//            if(0 == (Integer)param.get("tipsShow")){//不显示商品标题和简介
//                for(Map<String,Object> gm : maps){
//                    gm.put("goodsName","");
//                    gm.put("introduce","");
//                }
//            }
//        }
        return new PageInfo<>(maps);
    }

    /**
     * 分组为默认/全部且groupIdOrg有值
     */
    private boolean judge(Map<String, Object> param) {
        boolean b = param.get("groupId") == null || "0".equals(param.get("groupId").toString()) || "-1".equals(param.get("groupId").toString());
        return b && param.get("groupIsOrg") != null;
    }

    @Override
    public List<Map<String, Object>> listClassificationByGroupId(Map<String, Object> param) {
        List<Map<String, Object>> maps;
        Integer groupIsOrg;
        if (this.judge(param)) {
            // 默认分组
            groupIsOrg = Integer.valueOf(param.get("groupIsOrg").toString());
        } else {
            groupIsOrg = classificationDao.countGroupIsOrg(param);
        }
        if (groupIsOrg == null) {
            groupIsOrg = 1;
        }
        Integer showType = (Integer)param.get("showType");
        switch (showType){
            case 2 :
                if (groupIsOrg == 1) {
                    maps = classificationDao.listGoodsByGroupId(param);
                } else {
                    maps = classificationDao.listGoodsByGroupIdAndCustomerId(param);
                }
                break;
            case 1 :
                maps = classificationDao.getListGoodsCustom(param);
                break;
            default:
                throw GlobalException.build("参数错误");
        }
//        List<Map<String, Object>> maps = classificationDao.listGoodsByGroupId(param);
        List<Map<String, Object>> result = new ArrayList<>();
        if (!param.containsKey("pid")) {
            // 大类目
            Map<Object, Long> pClassificationId = maps.stream()
                    .filter(x -> x.get("pClassificationId") != null)
                    .collect(Collectors.groupingBy(x -> x.get("pClassificationId"), Collectors.counting()));
            Map<String, Object> all = new HashMap<>();
            all.put("id", null);
            all.put("name", "全部");
            all.put("count", maps.size());
            result.add(0, all);
            int i = maps.size();
            for (Object o : pClassificationId.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", o);
                String classificationName = classificationDao.getClassificationNameById(Integer.valueOf(o.toString()));
                map.put("name", classificationName);
                map.put("count", pClassificationId.get(o));
                result.add(map);
                i -= pClassificationId.get(o);
            }
            if (i > 0) {
                Map<String, Object> other = new HashMap<>();
                other.put("id", 0);
                other.put("name", "其他");
                other.put("count", i);
                result.add(other);
            }
        } else {
            // 小类目
            String pid = param.get("pid").toString();
            Map<Object, Long> collect = maps.stream()
                    .filter(x -> {
                        Object pClassificationId = x.get("pClassificationId");
                        if (pClassificationId != null) {
                            return pid.equals(pClassificationId.toString());
                        }
                        return false;
                    })
                    .collect(Collectors.groupingBy(x -> x.get("classificationId"), Collectors.counting()));
            for (Object o : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", o);
                String classificationName = classificationDao.getClassificationNameById(Integer.valueOf(o.toString()));
                map.put("name", classificationName);
                map.put("count", collect.get(o));
                result.add(map);
            }
        }

        return result;
//        List<Integer> classificationId = maps.stream()
//                .map(x -> (Integer) x.get("classificationId"))
//                .distinct()
//                .collect(Collectors.toList());
//        String classificationIds = StringUtils.join(classificationId, ",");
//        param.put("classificationIds", classificationIds);
//        if (!param.containsKey("pid")) {
//            List<Map<String, Object>> maps1;
//            Integer count;
//            if (groupIsOrg == 1) {
//                maps1 = classificationDao.listPidByClassificationId(param);
//                count = classificationDao.countGoodsNumByGroupIdWhereClassificationIdIsNull(param);
//            } else {
//                maps1 = classificationDao.listPidByClassificationIdAndCustomerId(param);
//                count = classificationDao.countGoodsNumByGroupIdAndCustomerIdWhereClassificationIdIsNull(param);
//            }
//            if (count > 0) {
//                Map<String, Object> other = new HashMap<>();
//                other.put("id", 0);
//                other.put("name", "其他");
//                other.put("count", count);
//                maps1.add(maps1.size(), other);
//            }
//            Map<String, Object> all = new HashMap<>();
//            all.put("id", null);
//            all.put("name", "全部");
//            int sum = maps1.stream()
//                    .mapToInt(x -> Integer.valueOf(x.get("count").toString()))
//                    .sum();
//            all.put("count", sum);
//            maps1.add(0, all);
//            return maps1;
//        } else {
//            if (groupIsOrg == 1) {
//                return classificationDao.listIdByClassificationIdAndPid(param);
//            } else {
//                return classificationDao.listIdByClassificationIdAndPidAndCustomerId(param);
//            }
//        }
    }

    @Override
    public PageInfo listGoodsCustom(Map<String, Object> param) {
        Integer pageIndex = (Integer) param.get("pageIndex");
        Integer pageSize = (Integer) param.get("pageSize");
        if(null == pageIndex) pageIndex = 1;
        if(null == pageSize) pageSize = 10;

        PageHelper.startPage(pageIndex, pageSize);
        Integer moduleType = (Integer)param.get("moduleType");
        param.put("moduleType",moduleType);
        List<Map<String, Object>> list = classificationDao.getListGoodsCustom(param);
        return new PageInfo<>(list);
    }

    @Override
    public Map<String, Object> getModuleInfo(Map<String, Object> param) {
        return classificationDao.getModuleInfo(param);
    }
}
